NameError: name 'FileNotFoundError' is not defined的解决方案

您所在的位置:网站首页 Python filenotfound NameError: name 'FileNotFoundError' is not defined的解决方案

NameError: name 'FileNotFoundError' is not defined的解决方案

#NameError: name 'FileNotFoundError' is not defined的解决方案| 来源: 网络整理| 查看: 265

处理文件不存在使用FileNotFoundError来处理异常

python版本:2.7

python代码:

filename='waiwai.txt' try: with open(filename) as f_obj: contents=f_obj.read() except FileNotFoundError: print "Sorry,the file does't exist."

运行结果:

Traceback (most recent call last): File "J:/Python/821_03.py", line 5, in except FileNotFoundError: NameError: name 'FileNotFoundError' is not defined Process finished with exit code 1

报错原因:

FileNotFoundError为python3使用的文本不存在异常处理方法

在python2.7中使用IOError

修改后的python代码

filename='waiwai.txt' try: with open(filename) as f_obj: contents=f_obj.read() except IOError: print "Sorry,the file does't exist." 运行结果:

Sorry,the file does't exist. Process finished with exit code 0



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3